package client

import (
	"net"
	"strings"
	"time"
)

type server struct {
	conn net.Conn
	er   chan bool
	writ chan bool
	recv chan []byte
	send chan []byte
}

func (s *server) read() {
	//isheart与timeout共同判断是不是自己设定的SetReadDeadline
	var isheart bool = false
	//20秒发一次心跳包
	s.conn.SetDeadline(time.Now().Add(time.Second * 20))
	for {
		var recv []byte = make([]byte, 10240)
		n, err := s.conn.Read(recv)
		if err != nil {
			if strings.Contains(err.Error(), "timeout") && !isheart {
				s.conn.Write([]byte("hh"))
				//4秒时间收心跳包
				s.conn.SetDeadline(time.Now().Add(time.Second * 4))
				isheart = true
				continue
			}
			//浏览器有可能连接上不发消息就断开，此时就发一个0，为了与服务器一直有一条tcp通路
			s.recv <- []byte("0")
			s.er <- true
			s.writ <- true
			break
		}
		//收到心跳包
		if recv[0] == 'h' && recv[1] == 'h' {
			s.conn.SetReadDeadline(time.Now().Add(time.Second * 20))
			isheart = false
			continue
		}
		s.recv <- recv[:n]
	}
}

func (s *server) write() {
	for {
		var send []byte = make([]byte, 10240)

		select {
		case send = <-s.send:
			s.conn.Write(send)
		case <-s.writ:
			break
		}
	}
}
